<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <h1>首页</h1>
  <input type="file" name="file" id="file"/>
  <hr>
  <div>
    预览
    <img id="img" src="" alt="">
  </div>
  <script>
    var file = document.querySelector('#file')
    var img = document.getElementById('img')
    file.addEventListener('change', function(t) {
      var file = t.target.files[0]
      var formData = new FormData()
      formData.append('file', file)
      request({
        url: '/uploadFile',
        method: 'POST',
        data: formData,
        success: function(res) {
          img.setAttribute('src', res.data.url)
        },
        error: function(e) {
          console.log(e)
        },
        progress: function(curloading) {
          console.log(curloading)
        }
      })
    })
    function request(options) {
      try {
        // 请求方式 默认GET
        var method = options.method || 'GET'
        // 同异步
        var async = options.async || true
        if(!options.url) return console.warn('请给请求添加url属性')
        // 发送请求得数据
        var formData = options.data
        var xhr = new XMLHttpRequest()
        /**
         * readyState 改变时执行
         * 0: 请求未初始化
         * 1: 服务器连接已建立
         * 2: 请求已接收
         * 3: 请求处理中
         * 4: 请求已完成，且响应已就绪 
         */
        xhr.onreadystatechange = function() {
          console.log(xhr.readyState, xhr.status)
          if (xhr.readyState === 4 && xhr.status === 200) {
            options.success(JSON.parse(xhr.responseText))
          }
        }
        /*
         * 上传文件进度
         */
        xhr.upload.onprogress = function (evt) {
          let loaded = evt.loaded
          let tot = evt.total
          let per = Math.floor(100 * loaded / tot) 
          options.progress(per)
        }
        /**
         * 规定请求方式，地址，以及是否异步 
         */
        xhr.open(method, options.url, async)
        // 发送请求
        xhr.send(formData)
      } catch (e) {
        options.error(e)
      }
    }
  </script>
</body>
</html>